package com.bigshen.algorithm.lString.solution02ReverseWordsInAStringIII;

/**
 * 557. Reverse Words in a String III 557. 反转字符串中的单词 III
 * Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
 *
 * Example 1:
 * Input: "Let's take LeetCode contest"
 * Output: "s'teL ekat edoCteeL tsetnoc"
 * Note: In the string, each word is separated by single space and there will not be any extra space in the string.
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Solution {
    public String reverseWords(String s) {
        if (null == s || s.trim().length() == 0) {
            return s;
        }
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < words.length;  i ++) {
            // 遍历单词、反转
            char[] chars = words[i].toCharArray();
            int start = 0;
            int end = chars.length - 1;
            while (start < end) {
                char tmp = chars[start];
                chars[start++] = chars[end];
                chars[end--] = tmp;
            }
            sb.append(new String(chars) + " ");
        }
        return sb.toString().trim();
    }
}
